package com.wuercloud.config.task;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by JiangWL on 2017/3/1.
 */
@Configuration
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {
    @Autowired
    private Environment environment;

    @Override
    @Bean("httpThreadTaskExecutor")
    public ThreadPoolTaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数
        taskExecutor.setCorePoolSize((environment.getProperty("thread.corePoolsize")==null) ? 4 : Integer.parseInt(environment.getProperty("thread.corePoolsize")));
        //最大线程数
        taskExecutor.setMaxPoolSize((environment.getProperty("thread.maxPoolsize")==null) ? 8 : Integer.parseInt(environment.getProperty("thread.maxPoolsize")));
        //线程池维护线程所允许的空闲时间
        taskExecutor.setKeepAliveSeconds((environment.getProperty("thread.keepAliveSeconds")==null) ? 500 : Integer.parseInt(environment.getProperty("thread.keepAliveSeconds")));
        //队列最大长度 >=mainExecutor.maxSize
        taskExecutor.setQueueCapacity((environment.getProperty("thread.queueCapacity")==null) ? 25 : Integer.parseInt(environment.getProperty("thread.queueCapacity")));

        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();
        taskExecutor.setThreadNamePrefix("520WAWA-HTTP-EXECUTOR::");
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable ex,Method method, Object... params) {
                System.out.println(ex.getMessage());
            }
        };
    }
}
